package cc.rengu.igas.mcps.common.util;

import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.StringUtil;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class ImageUtil {

    /**
     * 循环压缩图片方法
     *
     * @param srcData 源图片数据
     * @param maxSize 允许最大size
     * @param scale   压缩比例
     * @return 压缩后图片数据
     */
    public static byte[] commpressPicForScale(byte[] srcData, long maxSize, double scale) {

        maxSize = maxSize * 1024;
        byte[] imgData = Arrays.copyOf(srcData, srcData.length);

        if (imgData.length > maxSize) {
            do {
                try {
                    imgData = compress(imgData, scale);
                } catch (Exception e) {
                    throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                }
            } while (imgData.length > maxSize);
        }

        return imgData;
    }

    /**
     * 压缩图片方法
     *
     * @param srcImgData 图片数据
     * @param scale      压缩比例
     * @return 图片数据
     * @throws IOException 异常
     */
    private static byte[] compress(byte[] srcImgData, double scale) throws IOException {

        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData));
        //源图宽度
        int width = (int) (bi.getWidth() * scale);
        //源图高度
        int height = (int) (bi.getHeight() * scale);

        Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = tag.getGraphics();
        g.setColor(Color.RED);
        g.drawImage(image, 0, 0, null);
        g.dispose();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ImageIO.write(tag, "JPEG", bout);

        return bout.toByteArray();
    }

    /**
     * 将图片数据输入到文件
     *
     * @param imageData 图片数据
     * @param filePath  文件地址
     * @throws IOException 异常
     */
    public static void imageByte2File(byte[] imageData, String filePath) {

        if (imageData.length < 3 || StringUtil.isEmptyOrNull(filePath)) {
            return;
        }
        FileImageOutputStream imageOutPut = null;
        try {
            imageOutPut = new FileImageOutputStream(new File(filePath));
            imageOutPut.write(imageData, 0, imageData.length);
            imageOutPut.close();
        } catch (IOException ioe) {

        } finally {
            if (null != imageOutPut) {
                try {
                    imageOutPut.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
